﻿#include <string.h>
#include <stdio.h>
#include "type_cpp14.h"
#include "serialport.h"
#include "../support/OsSupport.h"

using namespace Support;
using namespace Serial_Port;

#ifdef WIN32
char default_portname[] = "COM69";
byte default_send_buf[] = "('w') get 2333\n";
#endif // WIN

#ifdef UNIX
char portname[] = "/dev/ttyUSB0";
#endif // UNIX

int baudrate = 115200;
char* portname = default_portname;
byte* send_data = default_send_buf;


byte recv_buf[1024];

// 解析命令行参数的函数
void parseArguments(int argc, char* argv[]) {
	for (int i = 1; i < argc; i++) {
		if (strncmp(argv[i], "-B:", 3) == 0) {
			baudrate = atoi(argv[i] + 3);
		} else if (strncmp(argv[i], "-P:", 3) == 0) {
			portname = argv[i] + 3;
		} else if (strncmp(argv[i], "-D:", 3) == 0) {
			send_data = reinterpret_cast<byte*>(argv[i] + 3);
		} else {
			printf("Unknown parameter: %s\n", argv[i]);
		}
	}
}


int main(int argc, char* argv[]) {
	fflush(stdout);
	parseArguments(argc, argv);
	printf("启动串口测试，以%d波特率，打开端口 %s，\n", baudrate, portname);
	printf("发送数据：%s\n", send_data);
	
	size_t send_length = strlen(reinterpret_cast<char*>(send_data));
	printf("发送数据长度：%zu\n", send_length);

	auto main_sp(std::make_unique<SerialPort>()); 

	main_sp->setPort(portname);
	main_sp->setBaud(baudrate);
	
	main_sp->openPort();
	tUs last_time = getTimesUs()+1000000;
	while (1) {
		int len;
		main_sp->recv(recv_buf, len, sizeof(recv_buf));
		if (len > 0) {
			printf("收到：%s\n", recv_buf);
		}
		fflush(stdout);
		tUs now_time = getTimesUs();
		if (now_time > last_time) {
			main_sp->send(send_data, send_length);
			last_time = now_time + 1000000;
			printf("send once\n");
		}
	}
}